import React, {Component} from 'react';
import './index.less';

import {base} from 'nc-lightapp-front';

import proFetch from '../../../../../hrpub/common/utils/project-fetch';
import deepCopy from '../../../../../hrpub/common/utils/deep-copy';

const {NCTabs, NCMenu, NCIcon} = base;
const {NCSubMenu, Item} = NCMenu;
const {NCTabPane} = NCTabs;

let tableDataCache = {};

let lastTab = '';


export default class SubSetTableCard extends Component {
    constructor(props) {
        super(props);
        if(props.use) {
            // 先这样写，解决首次点开显示子集时表格不出来
            props.use.editTable(...props.cardTableList)
        }
        
        this.state = {
            activeKey: '',
            tableList: [],
            businessSets: [],
            currentRowData: {
                record: {
                    values: {}
                }
            }
        };

        this.changeTab = this.changeTab.bind(this);
        this.initSubSet = this.initSubSet.bind(this);
        this.getTableTmp = this.getTableTmp.bind(this);
        this.makeGetTmpOpt = this.makeGetTmpOpt.bind(this);
        this.renderTabName = this.renderTabName.bind(this);
        this.renderSubMenu = this.renderSubMenu.bind(this);
        this.quickClickItem = this.quickClickItem.bind(this);
    }

    componentWillUnmount() {

    }


    // 获取模版的参数
    makeGetTmpOpt() {
        const {
            editTable,
            orgVal,
            mainTableId,
            table,
            func_type = '2'
        } = this.props;

        let rowData = {};
        if (mainTableId === 'ncc60071702list') {
            rowData = table.getClickRowIndex(mainTableId);
        } else {
            rowData = editTable.getClickRowIndex(mainTableId);
        }

        if (!rowData) {
            let allRows = {};

            if (mainTableId === 'ncc60071702list') {
                allRows = table.getAllTableData(mainTableId);
            } else {
                allRows = editTable.getAllRows(mainTableId);
            }

            if (allRows && allRows.length > 0) {
                rowData = {
                    index: 0,
                    record: allRows[0]
                };
            } else {
                return false;
            }
        }
        let postData = {
            func_type: func_type,
            pk_org: orgVal.refpk,
            pk_psnjob: rowData.record['pk_psnjob'] ? rowData.record['pk_psnjob'].value : rowData.record.values['pk_psnjob'].value
        };

        this.setState({
            currentRowData: deepCopy(rowData)
        });

        return postData;
    }

    // 获取模版的请求
    getTableTmp(postData) {
        return proFetch({
            url: '/nccloud/hrhi/psndoc/PsndocQueryOneAction.do',
            body: postData
        });
    }

    // 获取当前展示的子集的数据
    async getCurrentTableData(tableCode, pk_psnjob) {
        const {editTable, func_type = 2} = this.props;

        if (tableDataCache[tableCode]) {
            editTable.setTableData(tableCode, tableDataCache[tableCode], false);
            return;
        }

        let postData = {
            areaCode: tableCode,
            func_type: func_type,
            pk_psnjob: pk_psnjob
        };

        let res = await proFetch({
            url: '/nccloud/hrhi/psndoc/PsndocLoadSubDataAction.do',
            body: postData
        });

        if (res.success) {
            let tableData = {rows: []};
            if (res.data && res.data[tableCode]) {
                tableData = res.data[tableCode];
            }
            editTable.setTableData(tableCode, tableData);
            tableDataCache[tableCode] = deepCopy(tableData);
        }
    }

    // 初始化子集
    async initSubSet() {
        const {meta, editTable} = this.props;

        let template = meta.getMeta();
        let tableList = [];
        let postData = this.makeGetTmpOpt();
        let businessSets = [];
        tableDataCache = {};

        if (postData) {
            let res = await this.getTableTmp(postData);

            if (res.success && res.data) {
                let {
                    areaCodeList,
                    allArea,
                    busiSet
                } = res.data;

                tableList = [];
                businessSets = busiSet

                areaCodeList.forEach((item, index) => {
                    if (
                        !['ncc60071701list', 'sort'].includes(item) &&
                        template[item].moduletype === 'table'
                    ) {
                        template[item] = deepCopy(allArea[item]);
                        tableList.push(item);
                    }
                });
            }
        } else {
            Object.keys(template).forEach((key) => {
                let item = template[key];
                if (
                    item &&
                    item.moduletype === 'table' &&
                    !['ncc60071701list', 'sort'].includes(item.code)
                ) {
                    // console.log(item);
                    tableList.push(key);
                }
            });
        }
        meta.setMeta(template, () => {
            this.setState({
                tableList: tableList,
                activeKey: lastTab || tableList[0],
                businessSets: businessSets
            }, () => {
                if (postData) {
                    this.getCurrentTableData(lastTab || tableList[0], postData.pk_psnjob);
                }
            });
        });
    }

    changeTab(value) {
        const {
            currentRowData
        } = this.state;
        lastTab = value;
        this.setState({
            activeKey: value
        });

        this.getCurrentTableData(value, currentRowData.record['pk_psnjob'] ? currentRowData.record['pk_psnjob'].value : currentRowData.record.values['pk_psnjob'].value);
    }

    renderTabName(code) {
        const {meta} = this.props;
        const template = meta.getMeta();

        if (this.state.businessSets.includes(code)) {
            return (
                <span className="busi-tab">
                    {template[code].name}
                </span>
            );
        } else {
            return template[code].name
        }
    }

    quickClickItem({item, key, keyPath}) {
        this.changeTab(key);
    }

    renderSubMenu() {
        const {tableList} = this.state;
        const {meta, pageHeight, subHeight } = this.props;

        let template = meta.getMeta();

        return (
            <div className="sub-set-menu-wrapper">
                <NCMenu
                    mode="vertical"
                    className="sub-set-menu"
                    onClick={this.quickClickItem}
                    onOpenChange={(e) => {
                        setTimeout(() => {
                            let subDom = this.pageRef.querySelector('.u-menu-sub');
                            // subDom.style.height = pageHeight * 0.3 - 2 + 'px';
                            subDom.style.height = subHeight - 2 + 'px';
                        }, 1);

                    }}
                >
                    <NCSubMenu
                        title={<NCIcon type="uf-symlist"/>}
                        className="sub-set-submenu"
                    >
                        {tableList.map((item) => {
                            return (
                                <Item
                                    key={item}
                                >
                                    <a href="javascript:void(0)">
                                        {template[item].name}
                                    </a>
                                </Item>
                            );
                        })}
                    </NCSubMenu>
                </NCMenu>
            </div>
        );
    }

    render() {

        const {
            activeKey,
            tableList
        } = this.state;

        const {
            visible,
            editTable,
            meta,
            pageHeight,
            subHeight
        } = this.props;
        let subH = subHeight ? subHeight : pageHeight * 0.3

        return (
            <div
                className="sub-set-table-content"
                style={{
                    display: visible ? 'block' : 'none',
                    // height: pageHeight * 0.3
                    height: subH
                }}
                ref={ref => this.pageRef = ref}
            >
                <NCTabs
                    activeKey={activeKey}
                    onChange={this.changeTab}
                    extraContent={
                        <div style={{width: '50px', height: '30px'}}></div>
                    }
                >
                    {tableList.map((item) => {
                        return (
                            <NCTabPane
                                key={item}
                                tab={this.renderTabName(item)}
                            >
                                {editTable.createEditTable(item, {
                                    showIndex: true,
                                    // height: pageHeight * 0.3 - 80
                                    height: subH - 80
                                })}
                            </NCTabPane>
                        );
                    })}
                </NCTabs>
                {this.renderSubMenu()}
            </div>
        );
    }
}